package com.sinba.itsm.web;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class GetIPAddr
    implements Filter
{
    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
                  throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        this.getIpAddr( req );
        chain.doFilter( request, response );
    }

    public String getIpAddr( HttpServletRequest request )
    {
        String ip = request.getHeader( "x-forwarded-for" );

        if ( ( ip == null ) || ( ip.length(  ) == 0 ) || "unknown".equalsIgnoreCase( ip ) )
        {
            ip = request.getHeader( "Proxy-Client-IP" );
        }

        if ( ( ip == null ) || ( ip.length(  ) == 0 ) || "unknown".equalsIgnoreCase( ip ) )
        {
            ip = request.getHeader( "WL-Proxy-Client-IP" );
        }

        if ( ( ip == null ) || ( ip.length(  ) == 0 ) || "unknown".equalsIgnoreCase( ip ) )
        {
            ip = request.getRemoteAddr(  );
        }

//        System.out.println("--------Date:"+new Date()+"--IP:"+ip);
        return ip;
    }

    public void destroy(  )
    {
    }

    public void init( FilterConfig fConfig )
              throws ServletException
    {
    }
}
